import React, { useCallback, useEffect, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { Route, Routes, useNavigate } from 'react-router-dom';
import { message } from 'antd';
import _ from 'underscore';

import PrivateRoute from '@/hooks/PrivateRoute';
import Loading from '@/components/Loading';
import { baseRouters, addDynamicRoute } from "@/router";
import { flatRoutes } from '@/utils/routeUtils';
import LayoutLoader from '@/layout';
import { NOTFOUND } from '@/config/url';
import { getGrid, compile} from '@/utils';
import { validate, noticeUnreadNum } from '@/service';
import { setMessageCount, setUserInfo } from '@/reducers/main';
import Cookies from 'js-cookie';
import { useTranslation } from 'react-i18next';


function Application(props) {
    const [messageApi, contextHolder] = message.useMessage();
    const token = Cookies.get("portal_token");
    const { t } = useTranslation();

    const initState = () => ({
        loading: true,
        routerTree: baseRouters,
        routers: flatRoutes(baseRouters),
    }),
        [state, setState] = useState(initState),
        dispatch = useDispatch();
    const navigate = useNavigate();
    /**
     * 检查用户是否登录（也可以获取用户信息）
     *
     */
    const checkLogged = () => {
        let routes = state.routers || [],
            // {expire, user, token} = response?.data || {},
            authSource = [], // 后端返回的数据
            authRoutes = addDynamicRoute(authSource), // 这里需要传入后端返回的数据
            appRoutes = flatRoutes(routes.concat(authRoutes)), // 应用的所有路由
            routerTree = baseRouters.concat(authSource); // 原始路由数据

        window.SITE_CONFIG['appRouterTree'] = routerTree;
        window.SITE_CONFIG['appRouteArray'] = appRoutes;
        setState(o => ({
            ...o,
            loading: false,
            routers: appRoutes,
            routerTree,
        }));
        validate().then(response => {
            let { code, data } = response || {};
            setState(o => ({
                ...o,
                loading: false,
            }));
            if (code !== 0) {
                clearInfo();
            } else {
                const token = data?.token;
                const expire = data?.expire;
                const user = data?.user || {};
                Cookies.set('portal_token', token, { expires: expire });
                dispatch(setUserInfo(user));
                localStorage.setItem("portal_userinfo", compile(JSON.stringify(user)));
            }
        }).catch(e => {
            setState(o => ({
                ...o,
                loading: false,
            }));
        });
    };
    const clearInfo = () => {
        Cookies.remove('portal_token');
        // localStorage.removeItem('language');
        dispatch(setUserInfo({}));
        localStorage.removeItem("portal_userinfo");
    }

    /**
     * 监听页面宽度变化
     *
     */
    const resizeListen = useCallback(() => {
        let grid = getGrid();
        // dispatch(setStore({
        //     grid,
        //     isMobile: isMobileApp(grid),
        //     isPad: isPadApp(grid),
        //     isPc: isPcApp(grid),
        // }));
    }, []);

    // 这是入口文件，页面间切换不会触发，只有应用首次加载时才会触发
    useEffect(() => {
        checkLogged(); // 有单独的校验是否登录接口通过检验
        // 先执行一次屏幕宽度计算
        resizeListen();
        // 监听页面宽度变化，节流
        const handleResize = _.throttle(resizeListen, 200);
        window.addEventListener('resize', handleResize, false);
        return () => {
            window.removeEventListener('resize', handleResize, false);
        }
    }, []);
    const fetchMessageCount = async () => {
        try {
            const response = await noticeUnreadNum();
            const { code, data, message } = response;
            if (code == 0) {
                dispatch(setMessageCount(data));
            } else {
                messageApi.open({
                    type: 'error',
                    content: message,
                });
            }
        } catch (error) {
            if (error?.message) {
                messageApi.open({
                    type: 'error',
                    content: error.message,
                });
            }
        }
    };

    useEffect(() => {
        if (token) {
            fetchMessageCount();
            const interval = setInterval(fetchMessageCount, 60000);
            return () => clearInterval(interval);
        }
    }, [token]);
    return (
        <>
            {state.loading ? (
                <Loading tip={t('common.loading.tipTwo')} />
            ) : (
                <LayoutLoader routerTree={state.routerTree || []}>
                    <Routes>
                        {(state.routers || []).map(item => (
                            <Route
                                key={item.url}
                                path={item.url}
                                element={<PrivateRoute element={item.component} />}
                            />
                        ))}
                        <Route
                            path="*"
                            element={<PrivateRoute element={baseRouters.find(i => i.url === NOTFOUND)?.component || null} />}
                        />
                    </Routes>
                </LayoutLoader>
            )}
            {contextHolder}
        </>
    );
}

export default Application;


